<?php
class Search_RestController extends Ac_Rest_Controller
{

    /**
        return one random listing
     */
    public function indexAction() {
        $compressed = false;
        if (!empty($_GET['co'])) {
            $compressed = true;
            unset($_GET['co']);
        }

        file_put_contents('/tmp/api-search.txt', print_r($_GET, true), FILE_APPEND);

        $keyword    = !empty($_GET['kw']) ? $_GET['kw']: '';
        $page       = !empty($_GET['pg']) ? $_GET['pg']: 1;
        $per_page = 20;

        if (empty($keyword)) {
            throw new Ac_Exception_MissingInformation('Keyword is missing');
        }

        $res = $this->prepareSearch($page, $per_page);
        extract($res);
//        echo '<pre>'; var_dump($_GET, $res);exit;

        $listings = $list->response->docs;
        $list->response->numFound;

        $res = array(
            'info' => array(
                'nb' => $list->response->numFound,
            ),
        );

        //$i = 0;
        foreach ($listings as $ele) {
//echo '<pre>'; print_r($ele);exit;           
            $elem = Model_Listing::find($ele->id);
            if(!empty($elem)) {
//                $i++;
//                $res['listings'][] = $elem->exportRest();
                $tmp = $elem->exportRest($compressed);
                if($compressed) {
                    $tmp['_simplified'] = true;
                }
                $res['listings'] = $tmp;               
            } elseif(!empty($_GET['debug'])) {
                var_dump($ele->id);
                exit;
            }
        }
        //echo $i;
        //exit;
        echo json_encode($res);
        exit;
        //$this->_helper->json($res);
    }

    /**
        return one specific listing
     */
    public function getAction() 
    {
    }

    public function postAction() 
    {
    }



    private function prepareSearch($page, $per_page, $quiet = false)
    {
        //echo '<pre>';print_r($_GET);exit;

        //var_dump($this->_title);exit;
        $get = $_GET;
        if(empty($get['kw'])) {
            $get['kw'] = '';
        }

        $district   = !empty($_GET['ds']) ? $_GET['ds']: '';
        $page       = !empty($_GET['pg']) ? $_GET['pg']: 1;
        $get['price']   = !empty($_GET['pl']) ? $_GET['pl']: 0;
        $get['price-1'] = !empty($_GET['ph']) ? $_GET['ph']: 0;

        $get['keyword'] = $_GET['keyword'] = $get['kw'];
        unset($get['kw']);


        $get['keyword'] = !empty($_GET['keyword']) ? urldecode($_GET['keyword']) : '';
        $get['keyword'] = str_replace('-', ' ', $get['keyword']);

        $category = '';
        //print_r($_GET['category_list']);exit;
        $get['category_list'] = empty($get['small_category_list']) ? '' :$get['small_category_list'];
        $main_cat = false;
        if (Zend_Registry::isRegistered('category_list_id')) {
            $id  = Zend_Registry::get('category_list_id');            
            $cat = Model_Category::find($id);
            if (empty($cat->customization)) {
                $get['small_category_list'] = $id;
            }
            else {
                $get['small_category_list'] = $cat->customization;
            }            
            $get['category_list'] = $cat->customization;
            $main_cat = $cat->_id;
            $category = (string) $id;
            $_GET['small_category_list'] = $get['small_category_list'];
        }

        if (!empty($_GET['small_category_list'])) {
            $cat = Model_Category::find($_GET['small_category_list']);
            if (!empty($cat)) {
                $category = (string) $cat->_id;
                $main_cat = $cat->_id;
                if (empty($this->view->category)) {
                    //$this->view->category = $cat;
                }
            } elseif (empty($this->view->category)) {
                $test = $_GET['small_category_list'];
                if ($test == 'domestic-help') {
                    $test = 'maid';
                }
                //$cat = Model_Category::one(array('customization' => $test, 'path' => array('$size' => 3)));
                $cat = Model_Category::one(array('customization' => $test, 'path' => array('$size' => 3)));
                if ($cat === null) {
                    $cat = Model_Category::one(array('customization' => $test, 'path' => array('$size' => 2)));
                }
                if (!empty($cat) && $parent= $cat->getParent()) {
                    //$category = (string) $cat->_id;
                    $main_cat = $cat->path[0];
                    $get['category_list'] = $cat->_id;
                }
            }
        }

        $solr = Ac_Search::getClient();

        $get['sort'] = !empty($get['sort']) ? $get['sort'] : '';
        $classname = Model_Search::getListingInstance($get['category_list']);
        //print_r($_GET['category_list']);exit;
        //echo $get['keyword'];exit;
        //$listing   = new $classname;
        //
        $classname::processRefineSearchForm($get, $page, $per_page, $query, $fields, $additionalParameters);
        $classname::getFacetedSearch($additionalParameters);
        $title = '';

        if (!empty($main_cat)) {
            //echo 'cas1';
            $cat = Model_Category::find($main_cat);

            $main_cat = Model_Category::find($cat->path[0]);
            if (!Zend_Registry::isRegistered('page_title')) {            
                $title = $main_cat->page_title;
                if (empty($title)) {
                    $title = $main_cat->name;
                }
            }
            $description = $cat->description;
            if (!empty($main_cat)) {
                $main_cat = $main_cat->_id;
            } elseif (!empty($_GET['small_category_list'])) {
                //echo 'cas3';
                $main_cat = new MongoId($_GET['small_category_list']);
            }
        }
        if (!empty($_GET['sort'])) {
            $arr = $classname::getSearchResultSort();
            $sort = $this->view->t($arr[$_GET['sort']]);
        }

        //var_dump($main_cat->id);exit;
        if(!empty($main_cat)) {
            Zend_Registry::set('main_category', Model_Category::find($main_cat));
        }

        if (empty($additionalParameters['fq'])) {
            $additionalParameters['fq'] = '';
        }


        //Only show PUBLISHED Ads
        if (($cat = Model_Category::find(new MongoId($main_cat))) && $cat->id == 'mc52') {
            unset($additionalParameters['qf']);
            $additionalParameters['fq'] .= ' +status:1 +type_obj:'.  Model_Company::TYPE.'  +category:' . $category.' ';
        } else {
            if (empty($additionalParameters['fq'])) {
                //$additionalParameters['fq'] .= ' +status:1 +type_obj:'.Model_Listing::TYPE;
                $additionalParameters['fq'] .= ' +status:1 +type_obj_s:Model_Listing';
            }
            else {
                //$additionalParameters['fq'] .= ' +status:1 +type_obj:'.Model_Listing::TYPE;
                $additionalParameters['fq'] .= ' +status:1 +type_obj_s:Model_Listing';
            }
            if (!empty($category)) {
                $additionalParameters['fq'] .= ' +category:' . $category;
            }            
            if (!empty($district)) {
                $additionalParameters['fq'] .= ' +district:' . $district;
            }            
        }

        if(($main_cat=="4cda3e818835c16810e40000") && (empty($_GET['sort']) || $_GET['sort'] == 'recent')){
            $additionalParameters['sort'] = "created_at desc";
        }
        
        if (!empty($_GET['debug'])) {
            echo '<pre style="clear:both">';
            var_dump($_GET);
            var_dump('Page: '.$page, 'Per_apge: '.$per_page, 'query:'.$query);
            var_dump($additionalParameters);
            if (!empty($additionalParameters['qf'])) {
                print_r($additionalParameters['qf']);
            }
            echo '</pre>';
        }
        
        if (empty($query)) {
            $query = '*:*';
            $additionalParameters['q.alt'] = $query;
            unset($additionalParameters['defType']);
        }
        $start = ($page-1) * $per_page;
        $list = $solr->search($query, $start, $per_page, $additionalParameters);


        return array('list' => $list,
            'query' =>$query,
            'classname' =>$classname,
            'additionalParameters' => $additionalParameters,
        );
    }    
}

